package FileServer;

import Share.*;

import java.io.*;

public class Server {
	
	public static final int MAX_PORT_NUMBER = 65535;
	private static final int DEFAULT_CA_PORT = 5050;
	private static final int DEFAULT_SERVER_PORT = 4040;
	
	private static void printHelp()
	{
		System.out.println("Usage:server <ca host>[:<ca port>] [<receive token port>]");
		System.out.format("If not specified the default receive token port is %1$d.", DEFAULT_SERVER_PORT);
		System.out.println();
	}
	
	private static int getPort(String portStr)
	{
		int port;
		try
		{
			port = Integer.parseInt(portStr);
		}
		catch (NumberFormatException error)
		{
			port = -1;
		}
		
		if(port < 0 || port > MAX_PORT_NUMBER)
		{
			System.out.println("Invalid port number");
			port = -1;
		}
		return port;
	}
	
	public static void main(String[] args)
	{
		int port = DEFAULT_SERVER_PORT;
		int caPort = DEFAULT_CA_PORT;
		
		if(args.length < 1)
		{
			printHelp();
			return;
		}
		
		String[] caArg = args[0].split(":", 2);
		String ca = caArg[0];
		if(caArg.length > 1)
		{
			caPort = getPort(caArg[1]);
		}
		if(caPort < 0)
			return;
		
		if(args.length > 1)
		{
			port = getPort(args[1]);
		}
		if(port < 0)
			return;
		
		TransmitionBox box = new TransmitionBox();
		
		if(box.requestCertificate("server", ca, caPort) != TransmitStatus.success)
		{
			System.out.println("Unable to get server certificate.");
			return;
		}
		System.out.println("Certificate obtained.");
		
		try {
			box.waitConnection(port, new ServerHandler(box.getCertificate(),box.getPrivateKey()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
